#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QDateTime>
#include <QMessageBox>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("Client1");
    socket = new QTcpSocket;
    socketState = false;

    connect(socket, SIGNAL(disconnected()),this, SLOT(disconnectedSlot()));     //客户端断开连接
    connect(socket, SIGNAL(readyRead()),this, SLOT(readyReadSlot()));           //接收消息
}

Widget::~Widget()
{
    delete ui;
}

/*      开始连接        */
void Widget::on_pushButtonConnect_clicked()
{
    QString ipAddressStr = ui->lineEditAddress->text();
    quint16 port = ui->lineEditPort->text().toInt();

    if (!socketState)
    {
        socket->connectToHost(ipAddressStr, port);
        if (socket->waitForConnected(3000))
        {
            QMessageBox::information(this, "连接成功", "成功连接到服务器！");
            qDebug() << "Connect2Server OK";
            ui->pushButtonConnect->setText("断开连接");
            socketState = true;
        }
        else
        {
            QMessageBox::warning(this, "连接超时", "输入的IP地址或端口错误，连接超时，请检查后重试！");
            return;
        }
    }
    else
    {
        socket->close();
        ui->pushButtonConnect->setText("连接");
        socketState = false;
    }
}

// 在客户端断开连接时显示自身的IP地址和端口号
void Widget::disconnectedSlot()
{
    QString localIp = socket->localAddress().toString();
    quint16 localPort = socket->localPort();

    QString clientInfo = localIp + ":" + QString::number(localPort);
    QString str = QString(QDateTime::currentDateTime().toString("yyyy.MM.dd hh:mm:ss ddd")) +
                  " [" + clientInfo + "]" + " client close..";
    ui->textBrowserRecv->append(str);
    qDebug() << "Socket close";
}

// 在收到消息时显示发送方的IP地址和端口号以及消息内容等
void Widget::readyReadSlot()
{
    QByteArray dataBa = socket->readAll();
    QString message = QString::fromLocal8Bit(dataBa.data());

    // 假设服务器发送的消息格式为: "IP:Port|实际消息内容"
    int separatorIndex = message.indexOf("|");
    QString senderInfo;
    QString actualMessage;

    if (separatorIndex != -1) {
        // 解析发送方信息和实际消息
        senderInfo = message.left(separatorIndex);
        actualMessage = message.mid(separatorIndex + 1);
    } else {
        // 如果没有发送方信息，使用服务器信息
        QString peerIp = socket->peerAddress().toString();
        quint16 peerPort = socket->peerPort();
        senderInfo = peerIp + ":" + QString::number(peerPort);
        actualMessage = message;
    }

    // 格式化显示消息
    QString str = QString("%1 [%2] Recv\n%3")
                      .arg(QDateTime::currentDateTime().toString("yyyy.MM.dd hh:mm:ss ddd"))
                      .arg(senderInfo)
                      .arg(actualMessage);

    ui->textBrowserRecv->append(str);
}

void Widget::on_pushButtonSend_clicked()
{
    if (socketState)
    {
        QString dataStr = ui->textEditSend->toPlainText();
        QByteArray data = dataStr.toLocal8Bit();

        if (socket->isOpen() && socket->isValid())
        {
            socket->write(data);
        }

        QString localIp = socket->localAddress().toString();
        quint16 localPort = socket->localPort();

        QString clientInfo = localIp + ":" + QString::number(localPort);
        QString str = QString(QDateTime::currentDateTime().toString("yyyy.MM.dd hh:mm:ss ddd")) +
                      " [" + clientInfo + "]" + " Send\n" +
                      QString::fromLocal8Bit(data.data());
        ui->textBrowserRecv->append(str);
        ui->textEditSend->clear();
    }
    else
    {
        QMessageBox::warning(this, "未连接服务器", "请先连接到服务器后再发送消息！");
    }
}
